<template>
  <div>
     <van-cell title="我的频道">
<van-button type="default" round size="mini" @click="isEditShow = !isEditShow">{{isEditShow ? '完成' : '编辑'}}</van-button>
     </van-cell>
    <van-grid :gutter="10">
 <van-grid-item v-for="(value, index) in channels" :key="index" @click="myBtn(index,value)">
   <div class="name" :class="{active : active === index}">
     <span slot="text">{{value.name}}</span>
   </div>
      <van-icon name="close" v-show="isEditShow && index!==0" class="icon"/>
    </van-grid-item>
</van-grid>
<van-cell title="编辑频道">
     </van-cell>
    <van-grid :gutter="10">
  <van-grid-item v-for="(value, index) in  recommendChannels" :key="index" @click="btn(value)">
    <div class="name">
      <span>{{value.name}}</span>
    </div>
  </van-grid-item>
</van-grid>
  </div>
</template>

<script>
import { getAllChannels } from '@/api/user.js'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage.js'
import { addUserChannel, deleteUserChannel } from '@/api/channel.js'
export default {
  props: {
    channels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      isEditShow: false
    }
  },
  created () {
    this.loadAllChannels()
  },
  methods: {
    async loadAllChannels () {
      try {
        const res = await getAllChannels()
        console.log(res)
        this.list = res.data.data.channels
      } catch (err) {
        this.$toast('获取失败', err)
      }
    },
    async btn (value) {
      this.channels.push(value)
      if (this.user) {
      //  已登录
        try {
          await addUserChannel({
            id: value.id,
            seq: this.channels.length
          })
          this.$toast('添加成功')
        } catch (err) {
          this.$toast('获取失败')
        }
      } else {
      // 未登录
        setItem('todochannels', this.channels)
      }
    },
    async myBtn (index, value) {
      if (this.isEditShow) {
        if (index <= this.active) {
          this.$emit('update-active', this.active - 1, true)
        }
        this.channels.splice(index, 1)
        if (this.user) {
          try {
            await deleteUserChannel(value.id)
            this.$toast('删除成功')
          } catch {
            this.$toast('删除失败')
          }
        } else {
          setItem('todochannels', this.channels)
        }
      } else {
        this.$emit('update-active', index, false)
      }
    }
  },
  computed: {
    ...mapState(['user']),
    recommendChannels () {
      return this.list.filter(value => {
        return !this.channels.find(channel => {
          return channel.id === value.id
        })
      })
    }
  }
}
</script>

<style scoped>
.name {
  font-size: 10px;
}
.icon {
  position: relative;
 top: -74px;
 left: 80px;
 font-size: 30px;
}
 .active {
        color: red;
      }
</style>
